import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/utils/input_formatter_tools.dart';
import 'package:finance_app/src/widgets/button/normal_button.dart';
import 'package:finance_app/src/widgets/input/input_field.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import 'default_bottom_sheet.dart';

/// 修改基本收入来源
/// result
/// {
///       'amount': amountController.text,
///     }
showBasicIncomeTypeUpdateBottomSheet(
    BuildContext context, String amount) async {
  final result = await showDefaultBottomSheet(
    context,
    child: AddDiscountBottomSheet(
      amount: amount,
    ),
    title: S.current.basic_salary,
    isScrollControlled: true,
  );
  return result;
}

class AddDiscountBottomSheet extends StatefulWidget {
  final String amount;

  const AddDiscountBottomSheet({Key key, this.amount}) : super(key: key);

  @override
  _AddDiscountBottomSheetState createState() => _AddDiscountBottomSheetState();
}

class _AddDiscountBottomSheetState extends State<AddDiscountBottomSheet> {
  TextEditingController amountController = TextEditingController();
  FocusNode amountFocusNode = FocusNode();

  bool isEnable = false;

  void _onAdd() {
    if (amountController.text.length == 0) {
      BaseConfig.dialogBase.showToast(
          context: context, content: S.current.please_enter_the_amount);
      return;
    }
    Navigator.of(context).pop({
      'amount': amountController.text,
    });
  }

  @override
  void initState() {
    super.initState();
    if (widget.amount != null) {
      amountController.text = widget.amount;
    }
    amountController.addListener(_handleUpdateListener);
  }

  @override
  void dispose() {
    super.dispose();
    amountController.dispose();
    amountFocusNode.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: [
        AppSpaces.h20,
        InputField(
          tip: S.current.amount,
          controller: amountController,
          focusNode: amountFocusNode,
          inputFormatters: [
            doubleLimit2InputFormatter,
          ],
          keyboardType: TextInputType.numberWithOptions(decimal: true),
        ),
        AppSpaces.h30,
        NormalButton(
          title: S.current.done,
          onTap: isEnable ? _onAdd : null,
        ),
      ],
    );
  }

  void _handleUpdateListener() {
    if (amountController.text.length > 0) {
      if (isEnable == false) {
        setState(() {
          isEnable = true;
        });
      }
    } else {
      if (isEnable == true) {
        setState(() {
          isEnable = false;
        });
      }
    }
  }
}
